import { defineEventHandler } from 'h3';
import type { ResourceListResponse } from '#/api/resource-center/types';

export default defineEventHandler(
  async (event): Promise<ResourceListResponse> => {
    // 模拟延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 模拟统一资源数据
    const mockResources = [
      {
        id: 'cap-001',
        tenantId: 't-1001',
        name: '安排服务能力',
        code: 'spa.assign.service',
        type: 'CAPABILITY',
        systemStatus: 'ACTIVE',
        version: 'v1.3.0',
        labels: {
          domain: 'spa',
          category: 'business',
          priority: 'high',
        },
        annotations: {
          description: '用于安排SPA服务的核心能力',
          businessOwner: 'spa-team',
          technicalOwner: 'backend-team',
        },
        facets: {
          attributes: {
            bags: [
              {
                id: 'ability.core',
                domain: 'ABILITY',
                schema: {
                  type: 'object',
                  properties: {
                    maxConcurrent: { type: 'number' },
                    serviceTypes: { type: 'array', items: { type: 'string' } },
                  },
                },
                values: { maxConcurrent: 5, serviceTypes: ['SPA', 'MASSAGE'] },
              },
            ],
          },
          lifecycle: {
            currentState: 'ACTIVE',
            machine: {
              initial: 'ACTIVE',
              states: ['ACTIVE', 'INACTIVE'],
              transitions: [],
            },
          },
          behaviors: {
            definitions: [
              {
                id: 'start-service',
                name: '开始服务',
                kind: 'EXECUTION',
                steps: [
                  {
                    id: 'pick',
                    type: 'API_CALL',
                    config: { url: '/algo/pick', method: 'POST' },
                  },
                  {
                    id: 'occupy-room',
                    type: 'STATE_CHANGE',
                    config: { targetIdExpr: '$.result.roomId', to: 'OCCUPIED' },
                  },
                ],
                emits: ['SERVICE_STARTED'],
              },
            ],
          },
          events: {
            publish: [{ eventType: 'SERVICE_STARTED' }],
            subscribe: [
              {
                eventType: 'SERVICE_DONE',
                handler: {
                  actions: [
                    { type: 'CALL_BEHAVIOR', params: { behaviorId: 'settle' } },
                  ],
                },
              },
            ],
          },
          relations: {
            edges: [
              { to: { id: 'res-room-pool' }, kind: 'DEPENDS_ON' },
              { to: { id: 'res-therapist-pool' }, kind: 'DEPENDS_ON' },
            ],
          },
          capability: {
            category: 'BUSINESS',
            definition: { id: 'cap.def.001', code: 'spa.assign.service' },
            interfaces: [
              {
                id: 'rest.start',
                name: '开始服务',
                type: 'REST',
                endpoint: '/capabilities/spa.assign.service/start',
                method: 'POST',
                auth: { kind: 'JWT' },
                inputSchema: {
                  type: 'object',
                  properties: { customerId: { type: 'string' } },
                },
              },
            ],
          },
          versions: {
            history: [
              {
                version: 'v1.3.0',
                status: 'RELEASED',
                changelog: '优化服务分配算法',
                createdAt: '2025-01-25T10:00:00Z',
                createdBy: 'admin',
              },
            ],
          },
          monitoring: {
            metrics: ['response_time', 'success_rate'],
            alerts: [
              {
                id: 'alert-001',
                name: '响应时间告警',
                severity: 'WARNING',
                condition: 'response_time > 5000ms',
                actions: [
                  { type: 'EMAIL', params: { to: 'admin@example.com' } },
                ],
              },
            ],
          },
        },
        governance: {
          visibility: 'TENANT',
          owners: ['u-ops-01'],
          rbac: [
            { role: 'admin', permissions: ['read', 'write', 'delete'] },
            { role: 'user', permissions: ['read'] },
          ],
          approvals: [
            { step: 'technical_review', required: true },
            { step: 'business_approval', required: true },
          ],
        },
        createdAt: '2025-01-25T09:00:00Z',
        updatedAt: '2025-01-25T10:00:00Z',
      },
      {
        id: 'phy-001',
        tenantId: 't-1001',
        name: 'SPA房间-302',
        code: 'spa.room.302',
        type: 'PHYSICAL',
        systemStatus: 'ACTIVE',
        version: 'v1.0.0',
        labels: {
          location: 'floor-3',
          type: 'spa-room',
          capacity: '2',
        },
        annotations: {
          description: '3楼SPA房间，可容纳2人',
          equipment: ['massage-bed', 'shower', 'locker'],
        },
        facets: {
          attributes: {
            bags: [
              {
                id: 'room.basic',
                domain: 'RESOURCE',
                schema: {
                  type: 'object',
                  properties: {
                    area: { type: 'number' },
                    capacity: { type: 'number' },
                    facilities: { type: 'array', items: { type: 'string' } },
                  },
                },
                values: {
                  area: 25,
                  capacity: 2,
                  facilities: ['massage-bed', 'shower'],
                },
              },
            ],
          },
          lifecycle: {
            currentState: 'AVAILABLE',
            machine: {
              initial: 'AVAILABLE',
              states: ['AVAILABLE', 'OCCUPIED', 'MAINTENANCE'],
              transitions: [],
            },
          },
          behaviors: {
            definitions: [],
          },
          events: {
            publish: [
              { eventType: 'ROOM_OCCUPIED' },
              { eventType: 'ROOM_FREED' },
            ],
            subscribe: [],
          },
          relations: {
            edges: [],
          },
          versions: {
            history: [],
          },
          monitoring: {
            metrics: ['occupancy_rate', 'maintenance_count'],
            alerts: [],
          },
        },
        governance: {
          visibility: 'TENANT',
          owners: ['u-facility-01'],
          rbac: [],
          approvals: [],
        },
        createdAt: '2025-01-20T08:00:00Z',
        updatedAt: '2025-01-25T09:30:00Z',
      },
      {
        id: 'hum-001',
        tenantId: 't-1001',
        name: '张技师',
        code: 'therapist.zhang',
        type: 'HUMAN',
        systemStatus: 'ACTIVE',
        version: 'v1.0.0',
        labels: {
          department: 'spa',
          level: 'senior',
          specialties: 'massage,spa',
        },
        annotations: {
          description: '资深SPA技师，擅长按摩和SPA服务',
          experience: '5年',
          certifications: ['按摩师资格证', 'SPA技师证'],
        },
        facets: {
          attributes: {
            bags: [
              {
                id: 'employee.basic',
                domain: 'RESOURCE',
                schema: {
                  type: 'object',
                  properties: {
                    position: { type: 'string' },
                    experience: { type: 'number' },
                    skills: { type: 'array', items: { type: 'string' } },
                  },
                },
                values: {
                  position: 'SPA技师',
                  experience: 5,
                  skills: ['massage', 'spa'],
                },
              },
            ],
          },
          lifecycle: {
            currentState: 'AVAILABLE',
            machine: {
              initial: 'AVAILABLE',
              states: ['AVAILABLE', 'SERVING', 'OFF_DUTY'],
              transitions: [],
            },
          },
          behaviors: {
            definitions: [],
          },
          events: {
            publish: [
              { eventType: 'THERAPIST_AVAILABLE' },
              { eventType: 'SERVICE_COMPLETED' },
            ],
            subscribe: [],
          },
          relations: {
            edges: [],
          },
          versions: {
            history: [],
          },
          monitoring: {
            metrics: ['service_count', 'customer_rating'],
            alerts: [],
          },
        },
        governance: {
          visibility: 'TENANT',
          owners: ['u-hr-01'],
          rbac: [],
          approvals: [],
        },
        createdAt: '2025-01-15T09:00:00Z',
        updatedAt: '2025-01-25T10:15:00Z',
      },
    ];

    // 获取查询参数
    const query = getQuery(event);
    const pageNo = parseInt(query.pageNo as string) || 1;
    const pageSize = parseInt(query.pageSize as string) || 20;
    const keyword = query.keyword as string;
    const type = query.type as string;
    const status = query.status as string;

    // 过滤数据
    let filteredResources = mockResources;

    if (keyword) {
      filteredResources = filteredResources.filter(
        (resource) =>
          resource.name.includes(keyword) ||
          resource.code.includes(keyword) ||
          Object.values(resource.labels || {}).some((label) =>
            String(label).includes(keyword),
          ),
      );
    }

    if (type) {
      filteredResources = filteredResources.filter(
        (resource) => resource.type === type,
      );
    }

    if (status) {
      filteredResources = filteredResources.filter(
        (resource) => resource.systemStatus === status,
      );
    }

    // 分页
    const start = (pageNo - 1) * pageSize;
    const end = start + pageSize;
    const paginatedResources = filteredResources.slice(start, end);

    return {
      list: paginatedResources,
      total: filteredResources.length,
      pageNo,
      pageSize,
    };
  },
);
